package com.dzh.controller;

import com.alibaba.druid.filter.AutoLoad;
import com.dzh.mapper.UserMapper;
import com.dzh.pojo.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.web.servlet.server.Session;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.util.ResourceUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.UUID;

@Controller
public class Usercontroller {
    @Autowired
    private UserMapper userMapper;

    @RequestMapping("/tologin")
    public String tologin(){
        return "login";
    }

    @RequestMapping("/toregister")
    public String toregister(){
        return "register";
    }

    @RequestMapping("/toupdatemm")
    public String toupdatemm(Model model){
        return "updatemm";
    }



    @RequestMapping("/login")
    public String login(Model model, User user,String password,String username, HttpSession session){
        User userr  = userMapper.queryUserById(username,password);

        if(userr!=null){
            session.setAttribute("loginUser",username);
            return "index";
        }
        else{
             model.addAttribute("msg","密码或用户名有错误");
             return "login";
        }

    }

    @RequestMapping("/register")
    public String register(Model model, User user, HttpServletResponse response,String username,String password) {
     int count = userMapper.queryUserByusername(username);
     if(count == 1){
         model.addAttribute("msg","该用户名已被创建");
         return "register";
     }
     else{
         userMapper.addUser(username,password);
        return "login";
     }
    }

    @RequestMapping("/update")
    public String update(Model model, HttpServletResponse response, HttpServletRequest request,User user,String username){
     String password1 =    request.getParameter("password1");
     String password =   request.getParameter("password");
     System.out.println(password);
        System.out.println(password1);
        if(password.equals(password1)){
          int o =  userMapper.queryUserByusername(username);
          if(o==1){
              userMapper.updateUser(username,password);
              return "login";
          }
           else{
              model.addAttribute("msg","该用户不存在");
              return "updatemm";
          }
        }
        else {
            model.addAttribute("msg","两次输入密码不对");
            return "updatemm";
        }




    }



    @RequestMapping("/touserupdate")
    public String touserupdate(Model model,HttpSession session,HttpServletResponse response) throws IOException {
        response.setContentType("text/html;utf8");
        response.setCharacterEncoding("utf8");
        PrintWriter out=response.getWriter();
        String username =(String) session.getAttribute("loginUser");
        if(username==null){
            out.println("<script>alert('你尚未登录请先登录');</script>");
            return "login";
        }
       User user =  userMapper.queryUserByusername1(username);
        model.addAttribute("user1",user);
        return "userupdatebyhimself";

    }


    @RequestMapping("/userupdate")
    public String userupdate(@RequestParam("userimg") MultipartFile srcFile, RedirectAttributes redirectAttributes, HttpServletRequest request, Model model, HttpSession session,String username,String userphone)throws IOException{




        //前端没有选择文件，srcFile为空
//选择了文件，开始上传操作
        try {
//构建上传目标路径，找到了项目的target的classes目录
            File destFile = new File(ResourceUtils.getURL("classpath:").getPath());
            if(!destFile.exists()) {
                destFile = new File("");
            }
//输出目标文件的绝对路径
            System.out.println("file path:"+destFile.getAbsolutePath());
//拼接子路径
            SimpleDateFormat sf_ = new SimpleDateFormat("yyyyMMddHHmmss");
            String times = sf_.format(new Date());
            File upload = new File(destFile.getAbsolutePath(), "static/images/resource");
//若目标文件夹不存在，则创建
            if(!upload.exists()) {
                upload.mkdirs();
            }
            System.out.println("完整的上传路径："+upload.getAbsolutePath()+"/"+srcFile);

//根据srcFile大小，准备一个字节数组
            byte[] bytes = srcFile.getBytes();

//拼接上传路径
//Path path = Paths.get(UPLOAD_FOLDER + srcFile.getOriginalFilename());
//通过项目路径，拼接上传路径
            Path path = Paths.get(upload.getAbsolutePath()+"/"+srcFile.getOriginalFilename());

//** 开始将源文件写入目标地址
            Files.write(path, bytes);

            String uuid = UUID.randomUUID().toString().replaceAll("-", "");
// 获得文件原始名称
            String fileName = srcFile.getOriginalFilename();

// 获得文件后缀名称
            String suffixName = fileName.substring(fileName.lastIndexOf(".") + 1).toLowerCase();

// 生成最新的uuid文件名称
//            String newFileName = uuid + "."+ suffixName;
//            redirectAttributes.addFlashAttribute("message", "文件上传成功"+newFileName);
            System.out.println(fileName);
            System.out.println(path);
            String aaa ="images/resource/";
            String bbb1 = aaa+fileName;

            System.out.println(bbb1);


            userMapper.updateUserxinxi(username,bbb1,userphone,username);




        } catch (IOException e) {
            e.printStackTrace();
        }





        
        return "index";

    }



}
